#!/bin/bash
#自动生成配置文件
#set -x

ROOT=$(/Data/apps/php/bin/php -r "echo realpath('`dirname $0`/../');")

createlink() {
    echo "    create link $2 => $1"
    rm -f $2
    ln -s $1 $2
}
myecho() {
    echo -en $"\\033[0;32m $1 \\033[0;39m\n"
}

#部署阶段
PHP_DIR=$HOME/system/php
SERVICE_DIR=$HOME/system/services

rm -Rf $PHP_DIR
mkdir -p $PHP_DIR
mkdir -p $PHP_DIR/entity

rm -Rf $SERVICE_DIR
mkdir -p $SERVICE_DIR

#prepare for libs
ln -s $ROOT/libs $PHP_DIR/libs
exit; #就先到这，不从后台拿数据
#cat $ROOT/libs/service_common/dal_setting.dev.php | sed -e "s/\$USER/$USER/g" > $ROOT/libs/service_common/dal_setting.php

#prepare for baseclient
ln -s $ROOT/services/baseclient $PHP_DIR/baseclient

#prepare for clients and entitys and services
cd $ROOT/services
for service in `ls`; do
    if [ -d $ROOT/services/$service/src/interface/client ]; then
        ln -s $ROOT/services/$service/src/interface/client $PHP_DIR/${service}client
        ln -s $ROOT/services/$service $SERVICE_DIR/$service
    fi
    if [ -d $ROOT/services/$service/src/domain ]; then
        ln -s $ROOT/services/$service/src/domain $PHP_DIR/entity/$service
    fi
done

#初始化阶段
cd $SERVICE_DIR
for service in `ls`; do
    if [ -d $service/project ]; then
        myecho "开始创建$service子系统运行环境..."
        myecho "   创建服务端配置文件 => $SERVICE_DIR/$service/config/config.php"
        rm $SERVICE_DIR/$service/config/config.php
        cat $SERVICE_DIR/$service/config/server_template.php > $SERVICE_DIR/$service/config/config.php

        myecho "   创建客户端配置文件 => $SERVICE_DIR/$service/src/interface/client/config/client_conf.php"
        rm $SERVICE_DIR/$service/src/interface/client/config/client_conf.php
        cat $SERVICE_DIR/$service/config/client_template.php > $SERVICE_DIR/$service/src/interface/client/config/client_conf.php

        if [ ! -d $HOME/logs/client/$service ]; then
            myecho "   创建$service日志目录 $HOME/logs/client/$service"
            mkdir -p $HOME/logs/client/$service
        fi 

        if [ ! -d $HOME/logs/service/$service ]; then
            myecho "   创建$service日志目录 $HOME/logs/service/$service"
            mkdir -p $HOME/logs/service/$service
        fi

        if [[ $service != 'tu' ]]; then
            myecho "   创建nginx配置文件 => /Data/apps/nginx/conf/include/0.dev.$service.app.conf"
            cat $SERVICE_DIR/$service/config/nginx/template.conf | sed -e "s:/home/avatar:/home/dev:g" > $SERVICE_DIR/$service/config/nginx/dev.conf
            createlink $SERVICE_DIR/$service/config/nginx/dev.conf /Data/apps/nginx/conf/include/0.dev.$service.app.conf
        fi

        myecho "   创建assembly.php"
        /Data/apps/php/bin/php $SERVICE_DIR/$service/project/build.php $PHP_DIR 
    fi

    if [ -f $SERVICE_DIR/$service/project/init_env.sh ]; then
        myecho "   执行项目自定义初始化脚本  $SERVICE_DIR/$service/project/init_env.sh"
        bash $SERVICE_DIR/$service/project/init_env.sh
    fi
done
